from flask import Blueprint, request, jsonify
from app import db
from app.models.CourseResource import CourseResource
from app.models.Product import Product
from flask_jwt_extended import get_jwt_identity, jwt_required
from app.utils.response import success_api, fail_api
from app.utils.validator import validate_params
import uuid
from datetime import datetime
from ..base import base

# 获取课程资源列表
@base.route('/course_resource/list', methods=['GET'])
@jwt_required()
def get_resource_list():
    try:
        # 获取查询参数
        product_id = request.args.get('productId')
        resource_type = request.args.get('resourceType')
        status = request.args.get('status')

        # 构建查询条件
        query = CourseResource.query
        if product_id:
            query = query.filter(CourseResource.product_id == product_id)
        if resource_type:
            query = query.filter(CourseResource.resource_type == resource_type)
        if status:
            query = query.filter(CourseResource.status == status)

        # 按排序号排序
        resources = query.order_by(CourseResource.sort_order).all()
        
        # 返回结果
        return success_api(data=[resource.to_dict() for resource in resources])
    except Exception as e:
        return fail_api(msg=str(e))

# 获取课程资源详情
@base.route('/course_resource/<resource_id>', methods=['GET'])
@jwt_required()
def get_resource(resource_id):
    try:
        resource = CourseResource.query.get(resource_id)
        if not resource:
            return fail_api(msg='资源不存在')
        return success_api(data=resource.to_dict())
    except Exception as e:
        return fail_api(msg=str(e))

# 新增课程资源
@base.route('/course_resource', methods=['POST'])
@jwt_required()
def add_resource():
    try:
        data = request.get_json()
        
        # 参数校验
        required_fields = ['productId', 'title', 'resourceType', 'url']
        if not validate_params(data, required_fields):
            return fail_api(msg='缺少必要参数')

        # 检查商品是否存在
        product = Product.query.get(data.get('productId'))
        if not product:
            return fail_api(msg='关联的商品不存在')

        # 创建资源对象
        resource = CourseResource(
            resource_id=str(uuid.uuid4()),
            product_id=data.get('productId'),
            title=data.get('title'),
            resource_type=data.get('resourceType'),
            url=data.get('url'),
            duration=data.get('duration'),
            size=data.get('size'),
            sort_order=data.get('sortOrder', 0),
            status=data.get('status', '0')
        )

        # 保存到数据库
        db.session.add(resource)
        db.session.commit()

        return success_api(msg='添加成功')
    except Exception as e:
        db.session.rollback()
        return fail_api(msg=str(e))

# 修改课程资源
@base.route('/course_resource', methods=['PUT'])
@jwt_required()
def update_resource():
    try:
        data = request.get_json()
        
        # 参数校验
        required_fields = ['resourceId', 'title', 'resourceType', 'url']
        if not validate_params(data, required_fields):
            return fail_api(msg='缺少必要参数')

        # 查询资源
        resource = CourseResource.query.get(data.get('resourceId'))
        if not resource:
            return fail_api(msg='资源不存在')

        # 更新资源信息
        resource.title = data.get('title')
        resource.resource_type = data.get('resourceType')
        resource.url = data.get('url')
        resource.duration = data.get('duration')
        resource.size = data.get('size')
        resource.sort_order = data.get('sortOrder', resource.sort_order)
        resource.status = data.get('status', resource.status)
        resource.update_time = datetime.now()

        # 保存到数据库
        db.session.commit()

        return success_api(msg='修改成功')
    except Exception as e:
        db.session.rollback()
        return fail_api(msg=str(e))

# 删除课程资源
@base.route('/course_resource/<resource_id>', methods=['DELETE'])
@jwt_required()
def delete_resource(resource_id):
    try:
        resource = CourseResource.query.get(resource_id)
        if not resource:
            return fail_api(msg='资源不存在')

        # 从数据库中删除
        db.session.delete(resource)
        db.session.commit()

        return success_api(msg='删除成功')
    except Exception as e:
        db.session.rollback()
        return fail_api(msg=str(e))

# 更新资源排序
@base.route('/course_resource/sort', methods=['PUT'])
@jwt_required()
def update_resource_sort():
    try:
        data = request.get_json()
        if not isinstance(data, list):
            return fail_api(msg='参数格式错误')

        # 批量更新排序
        for item in data:
            resource_id = item.get('resourceId')
            sort_order = item.get('sortOrder')
            if resource_id and sort_order is not None:
                resource = CourseResource.query.get(resource_id)
                if resource:
                    resource.sort_order = sort_order

        # 保存到数据库
        db.session.commit()
        return success_api(msg='排序更新成功')
    except Exception as e:
        db.session.rollback()
        return fail_api(msg=str(e))